package com.example.administrator.express.db;

import android.content.Context;

import com.example.administrator.express.model.Role;
import com.example.administrator.express.model.Users;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.List;

public class UserDao {
    private Context context;
    private Dao<Users, Integer> userDaoOpe;
    private DatabaseHelper helper;

    public UserDao(Context context) {
        this.context = context;
        try {
            helper = DatabaseHelper.getHelper(context);
            userDaoOpe = helper.getDao(Users.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 增加一个用户
     *
     * @param user
     * @throws SQLException
     */
    public void add(Users user) {
        /*//事务操作
		TransactionManager.callInTransaction(helper.getConnectionSource(),
				new Callable<Void>()
				{

					@Override
					public Void call() throws Exception
					{
						return null;
					}
				});*/
        try {
            userDaoOpe.create(user);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public void  delete(Users users){
        try {
            userDaoOpe.delete(users);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void  update(Users users){
        try {
            userDaoOpe.update(users);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public Users get(int id) {
        try {
            Users users=null;
            users=userDaoOpe.queryForId(id);
            helper.getDao(Role.class).refresh(users.getRole());
            return users;


        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public List<Users> finall(){
        List<Users> list=null;
        try {
             list= userDaoOpe.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
    public Users getByLoginId(Integer loginId){
        List<Users> list=null;
        try {
       list=userDaoOpe.queryBuilder().where().eq("loginId",loginId).query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(list!=null&&list.size()>0){
            return list.get(0);
        }else{
            return null;
        }

    }

}
